package com.hoyue.servlet;

import com.hoyue.bean.Department;
import com.hoyue.service.DepartmentService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/DepartmentServlet")
public class DepartmentServlet extends HttpServlet {

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("method");//获取方法名
		if (name == null || name.isEmpty()) {
			throw new RuntimeException("没有传递method参数,请给出你想调用的方法");
		}
		Class c = this.getClass();//获得当前类的Class对象
		Method method = null;
		try {
			//获得Method对象
			method = getClass().getDeclaredMethod(name, HttpServletRequest.class, HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("没有找到" + name + "方法，请检查该方法是否存在");
		}

		try {
			method.invoke(this, request, response);//反射调用方法
		} catch (Exception e) {
			System.out.println("你调用的方法" + name + ",内部发生了异常");
			throw new RuntimeException(e);
		}
	}

	DepartmentService departmentService = new DepartmentService();

	/*后台显示数据库信息*/
	protected void getAdminDepartment(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		double randomNum = Math.random();
		request.setAttribute("randomNum", randomNum);

		List<Department> departments = departmentService.getAllList();
		request.setAttribute("departments", departments);
		request.getRequestDispatcher("/WEB-INF/admin/departments.jsp").forward(request, response);
	}

	/*后台增加数据库信息*/
	protected void addAdminDepartment(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Department depart = new Department();

		Map<String, Object> map = new HashMap<>();

		DiskFileItemFactory factory = new DiskFileItemFactory();

		ServletFileUpload sfu = new ServletFileUpload(factory);

		try {
			List<FileItem> items = sfu.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String fileName = item.getFieldName();
					String fileValue = item.getString("UTF-8");
					System.out.println(fileName + "------" + fileValue);
					map.put(fileName, fileValue);
				} else {
					String name = System.currentTimeMillis() + ".jpg";
					String photoFolder = this.getServletContext().getRealPath("page/images/department");
					System.out.println(photoFolder);

					InputStream inputStream = item.getInputStream();

					OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);

					IOUtils.copy(inputStream, outputStream);

					inputStream.close();
					outputStream.close();
					item.delete();

					map.put("picture_address", "page/images/department/" + name);
				}
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		try {
			BeanUtils.populate(depart, map);
		} catch (Exception e) {
			e.printStackTrace();
		}

		departmentService.addDepartment(depart);

		request.getRequestDispatcher(request.getContextPath() + "/DepartmentServlet?method=getAdminDepartment").forward(request, response);
	}

	/*后台修改数据库信息*/
	protected void updateAdminDepartment(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			String picture_address = request.getParameter("picture_address");
			Department depart = new Department();
			depart.setId(id); //更改id
			Map<String, Object> map = new HashMap<>();
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload sfu = new ServletFileUpload(factory);
			try {
				List<FileItem> items = sfu.parseRequest(request);

				System.out.println(items);
				for (FileItem item : items) {
					if (item.isFormField()) {
						String fileName = item.getFieldName();
						String fileValue = item.getString("UTF-8");
						map.put(fileName, fileValue);
					} else {
						if (item.getName().equals("")) {
							map.put("picture_address", picture_address);
							continue;
						}

						String name = picture_address.substring(picture_address.lastIndexOf("/") + 1);

						String photoFolder = this.getServletContext().getRealPath("page/images/department");

						InputStream inputStream = item.getInputStream();
						OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);

						IOUtils.copy(inputStream, outputStream);

						inputStream.close();
						outputStream.close();
						item.delete();

						map.put("picture_address", picture_address);
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}

			try {
				BeanUtils.populate(depart, map);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println(depart.getPicture_address());
			departmentService.updateDepartment(depart);
			response.sendRedirect(request.getContextPath() + "/DepartmentServlet?method=getAdminDepartment");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void deleteAdminDepartment(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		//查找地址
		String picPath = departmentService.getAddressById(id);
		String address = this.getServletContext().getRealPath(picPath);
		/*删除文件*/
		File file = new File(address);
		if (file.exists()) {
			file.delete();
		}
		departmentService.deleteDepartment(id);

		request.getRequestDispatcher(request.getContextPath() + "/DepartmentServlet?method=getAdminDepartment").forward(request, response);
	}

}
